/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package back;

import Definitions.Globals;
import Definitions.ManagerException;
import businessLogic.ManagerBeanLocal;
import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import model.Club;
import model.League;
import model.Offer;
import model.Player;

/**
 *
 * @author Jirka
 */
public class ManagerBack {

    @EJB
    private ManagerBeanLocal managerBean;
    private DataModel myOffersModel;
    private DataModel offersForMyPlayersModel;
    private DataModel leagueClubsModel;
    private DataModel goaltendersModel;
    private DataModel firstLineModel;
    private DataModel secondLineModel;
    private DataModel thirdLineModel;
    private DataModel fourthLineModel;
    private DataModel substitutesModel;
    private DataModel managersClubsModel;
    private String clubName;
    private String stadiumName;
    private String password;
    private String newPassword;
    private int leagueId;
    private String leagueName;
    private String leagueCountry;
    private int newSeats;
    private int offeredMoney;
    private Club club = null;
    private League league = null;
    private Player wantedPlayer = null;
    private HashMap<Player, String> positionsMap;

    public String getLeagueCountry() {
        return leagueCountry;
    }

    public int getLeagueId() {
        return leagueId;
    }

    public String getLeagueName() {
        return leagueName;
    }

    public void setLeagueCountry(String leagueCountry) {
        this.leagueCountry = leagueCountry;
    }

    public void setLeagueId(int leagueId) {
        this.leagueId = leagueId;
    }

    public void setLeagueName(String leagueName) {
        this.leagueName = leagueName;
    }

    public void setOfferedMoney(int offeredMoney) {
        this.offeredMoney = offeredMoney;
    }

    public int getOfferedMoney() {
        return offeredMoney;
    }

    public void setWantedPlayer(Player wantedPlayer) {
        this.wantedPlayer = wantedPlayer;
    }

    public Player getWantedPlayer() {
        return wantedPlayer;
    }

    public int getNewSeats() {
        return newSeats;
    }

    public void setNewSeats(int newSeats) {
        this.newSeats = newSeats;
    }

    public void setNewGPosition(String newPosition) {
        Player p = (Player) goaltendersModel.getRowData();
        if (positionsMap.containsKey(p)) {
            positionsMap.remove(p);
        }
        positionsMap.put(p, newPosition);
    }

    public void setNewL1Position(String newPosition) {
        Player p = (Player) firstLineModel.getRowData();
        if (positionsMap.containsKey(p)) {
            positionsMap.remove(p);
        }
        positionsMap.put(p, newPosition);
    }

    public void setNewL2Position(String newPosition) {
        Player p = (Player) secondLineModel.getRowData();
        if (positionsMap.containsKey(p)) {
            positionsMap.remove(p);
        }
        positionsMap.put(p, newPosition);
    }

    public void setNewL3Position(String newPosition) {
        Player p = (Player) thirdLineModel.getRowData();
        if (positionsMap.containsKey(p)) {
            positionsMap.remove(p);
        }
        positionsMap.put(p, newPosition);
    }

    public void setNewL4Position(String newPosition) {
        Player p = (Player) fourthLineModel.getRowData();
        if (positionsMap.containsKey(p)) {
            positionsMap.remove(p);
        }
        positionsMap.put(p, newPosition);
    }

    public void setNewSPosition(String newPosition) {
        Player p = (Player) substitutesModel.getRowData();
        if (positionsMap.containsKey(p)) {
            positionsMap.remove(p);
        }
        positionsMap.put(p, newPosition);
    }

    public String getNewGPosition() {
        Player p = (Player) goaltendersModel.getRowData();
        return positionsMap.get(p);
    }

    public String getNewL1Position() {
        Player p = (Player) firstLineModel.getRowData();
        return positionsMap.get(p);
    }

    public String getNewL2Position() {
        Player p = (Player) secondLineModel.getRowData();
        return positionsMap.get(p);
    }

    public String getNewL3Position() {
        Player p = (Player) thirdLineModel.getRowData();
        return positionsMap.get(p);
    }

    public String getNewL4Position() {
        Player p = (Player) fourthLineModel.getRowData();
        return positionsMap.get(p);
    }

    public String getNewSPosition() {
        Player p = (Player) substitutesModel.getRowData();
        return positionsMap.get(p);
    }

    public void setClubName(String clubName) {
        this.clubName = clubName;
    }

    public void setStadiumName(String stadiumName) {
        this.stadiumName = stadiumName;
    }

    public void setClub(Club club) {
        this.club = club;
    }

    public void setLeague(League league) {
        this.league = league;
    }

    public String getClubName() {
        return clubName;
    }

    public String getStadiumName() {
        return stadiumName;
    }

    public Club getClub() {
        if (club != null) {
            return club;
        }
        return getCurrentClub();
    }

    public League getLeague() {
        return league;
    }

    public String getLoginName() {
        Principal p = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
        String name = p.getName();
        try {
            if (managerBean.getManager() == null)
                managerBean.loginAndInit(name);

        } catch (ManagerException ex) {
            Logger.getLogger(ManagerBack.class.getName()).log(Level.SEVERE, null, ex);
        }
        positionsMap = new HashMap<Player, String>();
        return name;
//            return managerBean.getLoggedUser();
    }

    public DataModel getManagersClubsModel() {
        managersClubsModel = new ListDataModel(managerBean.getClubs());
        return managersClubsModel;
    }

    public void setManagersClubsModel(DataModel managersClubsModel) {
        this.managersClubsModel = managersClubsModel;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getNewPassword() {
        return newPassword;
    }

    public void setNewPassword(String newPassword) {
        this.newPassword = newPassword;
    }

    public String logout() {
        HttpSession sess = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        sess.invalidate();
        return "my-team";
    }

    public String editClub() {
        club = null;
        if (getCurrentClub() != null) {
            clubName = getCurrentClub().getName();
            stadiumName = getCurrentClub().getStadium().getName();
        }
        newSeats = 0;
        return "edit-club";
    }

    public String changeClub() {
        try {
            managerBean.renameCurrentClub(clubName);
        } catch (ManagerException ex) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(ex.getMessage()));
        }
        managerBean.renameCurrentClubStadium(stadiumName);
        return "edit-club";
    }

    public String editPassword() {
        password = null;
        newPassword = null;
        return "password";
    }

    public String changePassword() {
        try {
            managerBean.changePassword(password, newPassword);
        } catch (ManagerException ex) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(ex.getMessage()));
        }
        return "my-team";
    }

    public String browseOtherTeams() {
        league = managerBean.getAllLeagues().get(0);
        club = null;
        return "other-teams";
    }

    public String editOffers() {
        club = null;
        return "offers";
    }

    public String createClub() {
        club = null;
        this.clubName = "";
        this.stadiumName = "";

        return "create-club";
    }

    public String editTeam() {
        club = null;
        return "my-team";
    }

    public List<SelectItem> getAvailableLeaguesList() {
        List<SelectItem> items = new ArrayList<SelectItem>();
        for (League l : managerBean.getAvailableLeagues()) {
            items.add(new SelectItem(l, l.getName() + " (" + l.getCountry() + ")"));
        }
        return items;
    }

    public List<SelectItem> getAllLeaguesList() {
        List<SelectItem> items = new ArrayList<SelectItem>();
        for (League l : managerBean.getAllLeagues()) {
            items.add(new SelectItem(l, l.getName() + " (" + l.getCountry() + ")"));
        }
        return items;
    }

    public String saveClub() {
        try {
            managerBean.createClub(clubName, stadiumName, league);
        } catch (ManagerException ex) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(ex.getMessage()));
            return "";
        }
//        managerBean.switchClub(managerBean.getClub());

        return "my-team";
    }

    public DataModel getMyOffersModel() {
        myOffersModel = new ListDataModel(managerBean.lookupMyOffers());
        return myOffersModel;
    }

    public DataModel getOffersForMyPlayersModel() {
        offersForMyPlayersModel = new ListDataModel(managerBean.lookupOffersForMyPlayers());
        return offersForMyPlayersModel;
    }

    public String cancelOffer() {
        Offer offer = (Offer) myOffersModel.getRowData();
        managerBean.cancelOffer(offer);
        return "offers";
    }

    public String acceptOffer() {
        Offer offer = (Offer) offersForMyPlayersModel.getRowData();
        try {
            managerBean.acceptOffer(offer);
        } catch (ManagerException ex) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(ex.getMessage()));
        }
        return "offers";
    }

    public String denyOffer() {
        Offer offer = (Offer) offersForMyPlayersModel.getRowData();
        managerBean.denyOffer(offer);
        return "offers";
    }

    public String selectLeague() {
        return "other-teams";
    }

    public DataModel getLeagueClubsModel() {
        leagueClubsModel = new ListDataModel(managerBean.getLeagueClubs(league));
        return leagueClubsModel;
    }

    public void setLeagueClubsModel(DataModel leagueClubsModel) {
        this.leagueClubsModel = leagueClubsModel;
    }

    public DataModel getGoaltendersModel() {
        Club employer = getClub();
        goaltendersModel = new ListDataModel(managerBean.getClubGoaltenders(employer));
        return goaltendersModel;
    }

    public void setGoaltendersModel(DataModel goaltendersModel) {
        this.goaltendersModel = goaltendersModel;
    }

    public DataModel getFirstLineModel() {
        Club employer = getClub();
        firstLineModel = new ListDataModel(managerBean.getClubLinePlayers(employer, 1));
        return firstLineModel;
    }

    public DataModel getSecondLineModel() {
        Club employer = getClub();
        secondLineModel = new ListDataModel(managerBean.getClubLinePlayers(employer, 2));
        return secondLineModel;
    }

    public DataModel getThirdLineModel() {
        Club employer = getClub();
        thirdLineModel = new ListDataModel(managerBean.getClubLinePlayers(employer, 3));
        return thirdLineModel;
    }

    public DataModel getFourthLineModel() {
        Club employer = getClub();
        fourthLineModel = new ListDataModel(managerBean.getClubLinePlayers(employer, 4));
        return fourthLineModel;
    }



    public DataModel getSubstitutesModel() {
        Club employer = getClub();
        substitutesModel = new ListDataModel(managerBean.getClubSubstitutes(employer));
        return substitutesModel;
    }

    public String showTeam() {
        club = (Club) leagueClubsModel.getRowData();
        if (club.getManager().equals(managerBean.getManager())) {
            managerBean.switchClub(club);
            league = null;
//        getGoaltendersModel();
//        getLinePlayersModels();
//        getSubstitutesModel();
//        getMyOffersModel();
//        getOffersForMyPlayersModel();
            return "my-team";
        }
        wantedPlayer = null;
        offeredMoney = 0;
        return "team";
    }

    public Club getCurrentClub() {
        return managerBean.getClub();
    }

    public List<SelectItem> getPossibleGoaltenderPositions() {
        List<SelectItem> items = new ArrayList<SelectItem>();
        for (String pos : managerBean.getPossibleGoaltenderPositionsInClub(getClub())) {
            items.add(new SelectItem(pos, pos));
        }
        return items;
    }

    public List<SelectItem> getPossiblePositions() {
        List<SelectItem> items = new ArrayList<SelectItem>();
        for (String pos : managerBean.getPossiblePositionsInClub(getClub())) {
            items.add(new SelectItem(pos, pos));
        }
        return items;
    }

    public String switchPost(Player p) {
        String newPosition = positionsMap.get(p);
//        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(p.getFirstName() + " " + p.getSurname() + " " + p.getPositionInCurrentTeam() + "->" + newPosition ));
        if (newPosition.equals(p.getPositionInCurrentTeam())) {
            return "my-team";
        }
        managerBean.changePlayerPosition(p, newPosition);
        getGoaltendersModel();
        getFirstLineModel();
        getSecondLineModel();
        getThirdLineModel();
        getFourthLineModel();
        getSubstitutesModel();
        return "my-team";
    }

    public String clubsList() {
        club = null;
        return "clubs";
    }

    public String switchClub() {
        club = (Club) managersClubsModel.getRowData();
        managerBean.switchClub(club);
        league = null;
        getGoaltendersModel();
        getFirstLineModel();
        getSecondLineModel();
        getThirdLineModel();
        getFourthLineModel();
        getSubstitutesModel();
        getMyOffersModel();
        getOffersForMyPlayersModel();
        return "my-team";
    }

    public void switchGoaltender() {
        Player p = (Player) goaltendersModel.getRowData();
        switchPost(p);
    }

    public void switchFirstLine() {
        Player p = (Player) firstLineModel.getRowData();
        switchPost(p);
    }

    public void switchSecLine() {
        Player p = (Player) secondLineModel.getRowData();
        switchPost(p);
    }

    public void switchThirdLine() {
        Player p = (Player) thirdLineModel.getRowData();
        switchPost(p);
    }

    public void switchFourthLine() {
        Player p = (Player) fourthLineModel.getRowData();
        switchPost(p);
    }

    public void switchSubstitutes() {
        Player p = (Player) substitutesModel.getRowData();
        switchPost(p);
    }

    public String increaseCapacity() {
        try {
            managerBean.increaseStadiumCapacity(newSeats);
        } catch (ManagerException ex) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(ex.getMessage()));
        }
        return "edit-club";
    }

    public String improveEquipment() {
        try {
            managerBean.improveStadiumEquipment();
        } catch (ManagerException ex) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(ex.getMessage()));
        }
        return "edit-club";
    }

    public String buyGoaltender() {
        wantedPlayer = (Player) goaltendersModel.getRowData();
        return "team";
    }

    public String buy1stLinePlayer() {
        wantedPlayer = (Player) firstLineModel.getRowData();
        return "team";
    }

    public String buy2ndLinePlayer() {
        wantedPlayer = (Player) secondLineModel.getRowData();
        return "team";
    }

    public String buy3rdLinePlayer() {
        wantedPlayer = (Player) thirdLineModel.getRowData();
        return "team";
    }

    public String buy4thLinePlayer() {
        wantedPlayer = (Player) fourthLineModel.getRowData();
        return "team";
    }

    public String buySubstitute() {
        wantedPlayer = (Player) substitutesModel.getRowData();
        return "team";
    }

    public String makeOffer() {
        try {
            managerBean.createOffer(wantedPlayer, offeredMoney);
        } catch (ManagerException ex) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(ex.getMessage()));
            return "team";
        }
        club = null;
        return "offers";
    }

    public boolean getExistsAvailableLeague() {
        return managerBean.getAvailableLeagues().size() > 0;
    }

    public boolean getHasClub() {
        return managerBean.getClubs().size() > 0;
    }

    public boolean getIsInterestedInAnyPlayer() {
        return wantedPlayer != null;
    }

    public boolean getHasFourthLine() {
        return managerBean.getClubLinePlayers(getClub(), 4).size() > 0;
    }

    public String getSeatCost() {
        return Integer.toString(Globals.COST_PER_SEAT);
    }

    public String getImprovementCost() {
        return Integer.toString(Globals.EQUIPMENT_LEVEL_COST);
    }

    public boolean getIsAdmin() {
        if (FacesContext.getCurrentInstance().getExternalContext().isUserInRole("admin")) {
            return true;
        }
        return false;
    }

    public String createLeague() {
        this.leagueId=1;
        this.leagueName = "";
        this.leagueCountry = "";
        return "create-league";
    }

    public String saveLeague() {
        try {
            managerBean.createLeague(leagueId, leagueName, leagueCountry);
        } catch (ManagerException ex) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(ex.getMessage()));
            return "create-league";
        }
        return "other-teams";
    }
}
